package com.qs.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qs.controller.vo.FormDataVO;
import com.qs.mapper.FormDataMapper;
import com.qs.mapper.FormFieldMapper;
import com.qs.mapper.RoleMapper;
import com.qs.mapper.UserMapper;
import com.qs.mapper.entity.FormData;
import com.qs.mapper.entity.FormField;
import com.qs.mapper.entity.Role;
import com.qs.mapper.entity.User;
import com.qs.service.FormDataService;
import com.qs.service.bo.FormDataBO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class FormDataServiceImpl extends ServiceImpl<FormDataMapper, FormData> implements FormDataService {
    private final FormDataMapper formDataMapper;
    private final FormFieldMapper formFieldMapper;
    private final RoleMapper roleMapper;

    @Override
    public Page<List<FormData>> queryFormData(Long formId, Long current, Long size, String keyword) {
        Page<List<FormData>> result = new Page<>();
        String username = StpUtil.getLoginIdAsString();
        if (!"admin".equals(username)) {
            List<Role> roleList = roleMapper.getRoleListByUsername(username);
            for (Role role : roleList) {
                if ("all".equals(role.getName())) {
                    username = "admin";
                    break;
                }
            }
        }
        // 查询总共多少行数据 (符合过滤条件的)
        List<String> rowIdList = baseMapper.queryFormDataRow(formId, username, keyword);
        if (CollectionUtils.isEmpty(rowIdList)) {
            return result;
        }
        // 当前页应该展示的是哪些条
        List<String> currentRowIdList = rowIdList.subList((int) (size * (current - 1)), Math.min((int) (size * current), rowIdList.size()));
        List<FormData> formDataList = formDataMapper.queryFormData(formId, username, currentRowIdList);
        List<List<FormData>> list = new ArrayList<>(formDataList.stream().collect(Collectors.groupingBy(FormData::getRowId)).values());
        result.setTotal(rowIdList.size());
        result.setRecords(list);
        return result;
    }

    @Override
    @Transactional
    public String add(FormDataVO formDataVO) {
        Long formId = formDataVO.getFormId();
        String rowId = String.valueOf(System.currentTimeMillis());
        // 查询出所有的字段
        Map<String, Long> formFieldMap = new HashMap<>();
        LambdaQueryWrapper<FormField> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(FormField::getFormId, formId);
        List<FormField> formFieldList = formFieldMapper.selectList(lambdaQueryWrapper);
        formFieldList.forEach(formField -> {
            formFieldMap.put(formField.getName(), formField.getId());
        });
        List<FormData> formDataList = formDataVO.getData().stream().map(map -> {
            FormData formData = new FormData();
            formData.setFieldId(formFieldMap.get(map.get("key")));
            formData.setRowId(rowId);
            formData.setValue(map.get("value"));
            return formData;
        }).collect(Collectors.toList());

        FormData formData1 = new FormData();
        formData1.setRowId(rowId);
        formData1.setFieldId(formFieldMap.get("createUser"));
        formData1.setValue(StpUtil.getLoginIdAsString());
        formDataList.add(formData1);
        FormData formData2 = new FormData();
        formData2.setRowId(rowId);
        formData2.setFieldId(formFieldMap.get("createTime"));
        formData2.setValue(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        formDataList.add(formData2);
        FormData formData3 = new FormData();
        formData3.setRowId(rowId);
        formData3.setFieldId(formFieldMap.get("updateUser"));
        formData3.setValue(StpUtil.getLoginIdAsString());
        formDataList.add(formData3);
        FormData formData4 = new FormData();
        formData4.setRowId(rowId);
        formData4.setFieldId(formFieldMap.get("updateTime"));
        formData4.setValue(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        formDataList.add(formData4);
        boolean saved = saveBatch(formDataList);
        return saved ? "新增成功" : "新增失败";
    }

    @Override
    @Transactional
    public String edit(FormDataVO formDataVO) {
        Long formId = formDataVO.getFormId();
        String rowId = formDataVO.getRowId();
        // 获取该行的数据的创建人
        LambdaQueryWrapper<FormData> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(FormData::getFieldId, getFormFieldId(formId, "createUser")).eq(FormData::getRowId, rowId);
        String createUser = baseMapper.selectOne(lambdaQueryWrapper).getCreateUser();
        List<FormData> formDataList = formDataVO.getData().stream().map(map -> {
            Long fieldId = getFormFieldId(formId, map.get("key"));
            LambdaQueryWrapper<FormData> formDataLambdaQueryWrapper = Wrappers.lambdaQuery();
            formDataLambdaQueryWrapper.eq(FormData::getFieldId, fieldId).eq(FormData::getRowId, rowId);
            FormData formData = baseMapper.selectOne(formDataLambdaQueryWrapper);
            if (formData == null) {
                FormData newFormData = new FormData();
                newFormData.setFieldId(fieldId);
                newFormData.setRowId(rowId);
                newFormData.setValue(map.get("value"));
                newFormData.setCreateUser(createUser);
                baseMapper.insert(newFormData);
                return newFormData;
            }
            formData.setValue(map.get("value"));
            return formData;
        }).filter(formData -> Objects.nonNull(formData.getId())).collect(Collectors.toList());
        LambdaQueryWrapper<FormData> formDataLambdaQueryWrapper1 = Wrappers.lambdaQuery();
        formDataLambdaQueryWrapper1.eq(FormData::getFieldId, getFormFieldId(formId, "updateUser")).eq(FormData::getRowId, rowId);
        FormData formData1 = baseMapper.selectOne(formDataLambdaQueryWrapper1);
        formData1.setFieldId(getFormFieldId(formId, "updateUser"));
        formData1.setValue(StpUtil.getLoginIdAsString());
        formDataList.add(formData1);
        LambdaQueryWrapper<FormData> formDataLambdaQueryWrapper2 = Wrappers.lambdaQuery();
        formDataLambdaQueryWrapper2.eq(FormData::getFieldId, getFormFieldId(formId, "updateTime")).eq(FormData::getRowId, rowId);
        FormData formData2 = baseMapper.selectOne(formDataLambdaQueryWrapper2);
        formData2.setFieldId(getFormFieldId(formId, "updateTime"));
        formData2.setValue(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        formDataList.add(formData2);
        boolean saved = updateBatchById(formDataList);
        return saved ? "修改成功" : "修改失败";
    }

    private Long getFormFieldId(Long formId, String formFieldName) {
        LambdaQueryWrapper<FormField> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(FormField::getFormId, formId).eq(FormField::getName, formFieldName);
        FormField formField = formFieldMapper.selectOne(lambdaQueryWrapper);
        return formField.getId();
    }
}
